// Copyright (C) 2025 woodycpp
//
// This work is licensed under the Creative Commons Attribution-ShareAlike 4.0
// International License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/4.0/
//
// You are free to:
//   * Share — copy and redistribute the material in any medium or format
//   * Adapt — remix, transform, and build upon the material
//
// Under the following terms:
//   * Attribution — You must give appropriate credit, provide a link to the
//   license,
//     and indicate if changes were made. You may do so in any reasonable
//     manner, but not in any way that suggests the licensor endorses you or
//     your use.
//   * ShareAlike — If you remix, transform, or build upon the material, you
//   must
//     distribute your contributions under the same license as the original.
//
// In short: You must credit the original author (woodycpp, 2025) and share any
// derivative works under the same CC-BY-SA-4.0 license.

#include <gtest/gtest.h>
#include <string>

#include "print_last_kth.h"

TEST(printLastKthTest, NormalCase) {
    int arr[] = {1, 2, 3, 4, 5};
    LinkList list = CreateList(arr, 5);

    testing::internal::CaptureStdout();
    int result = printLastKth(list, 2);
    std::string output = testing::internal::GetCapturedStdout();

    EXPECT_EQ(result, 1);    // 期望返回成功
    EXPECT_EQ(output, "4");  // 期望输出 "4"
}

TEST(printLastKthTest, EmptyList) {
    int arr[] = {};
    LinkList list = CreateList(arr, 0);

    testing::internal::CaptureStdout();
    int result = printLastKth(list, 1);
    std::string output = testing::internal::GetCapturedStdout();

    EXPECT_EQ(result, 0);   // 期望返回失败
    EXPECT_EQ(output, "");  // 期望输出为空
}

TEST(printLastKthTest, KTooLarge) {
    int arr[] = {1, 2, 3, 4, 5};
    LinkList list = CreateList(arr, 5);

    testing::internal::CaptureStdout();
    int result = printLastKth(list, 6);
    std::string output = testing::internal::GetCapturedStdout();

    EXPECT_EQ(result, 0);   // 期望返回失败
    EXPECT_EQ(output, "");  // 期望输出为空
}

TEST(printLastKthTest, KIsOne) {
    int arr[] = {1, 2, 3, 4, 5};
    LinkList list = CreateList(arr, 5);

    testing::internal::CaptureStdout();
    int result = printLastKth(list, 1);
    std::string output = testing::internal::GetCapturedStdout();

    EXPECT_EQ(result, 1);    // 期望返回成功
    EXPECT_EQ(output, "5");  // 期望输出 "5"
}

TEST(printLastKthTest, KIsLength) {
    int arr[] = {1, 2, 3, 4, 5};
    LinkList list = CreateList(arr, 5);

    testing::internal::CaptureStdout();
    int result = printLastKth(list, 5);
    std::string output = testing::internal::GetCapturedStdout();

    EXPECT_EQ(result, 1);    // 期望返回成功
    EXPECT_EQ(output, "1");  // 期望输出 "1"
}